//
//  KeBiaoListViewController.m
//  LoveDraw
//
//  Created by 零零壹 on 2017/7/14.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "KeBiaoListViewController.h"
#import "KeBiaoTableViewCell.h"
#import "KeBiaoSecTableViewCell.h"
#import "PopWindowView.h"
#import "DatePickerView.h"
#import "NSDate+Extension.h"
#import "KeBiaoTongJiV.h"

@interface KeBiaoListViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger page;
    NSString *year;
    NSString *month;
}

@property(nonatomic,strong)UITableView *listV;
@property(nonatomic,strong)NSMutableArray *ListArr;
@property(nonatomic,strong)NSDateComponents* comp;
@property(nonatomic,strong)UIButton *custumBTN;
@property(nonatomic,strong)KeBiaoTongJiV *KebiaoV;
@property(nonatomic,assign)BOOL isHaveClick; // 可不可以统计

@end

@implementation KeBiaoListViewController

-(NSMutableArray *)ListArr
{
    if (!_ListArr) {
        _ListArr = [NSMutableArray array];
    }
    return _ListArr;
}

-(UITableView *)listV
{
    if (!_listV)
    {
        _listV = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KscreenW, KscreenH-64) style:(UITableViewStyleGrouped)];
        _listV.delegate = self;
        _listV.dataSource = self;
        _listV.backgroundColor = [UIColor whiteColor];
        _listV.estimatedSectionHeaderHeight = 0;
        _listV.estimatedSectionFooterHeight = 0;
        [_listV registerNib:[UINib nibWithNibName:@"KeBiaoTableViewCell" bundle:nil] forCellReuseIdentifier:@"KeBiaoTableViewCell"];
        [_listV registerNib:[UINib nibWithNibName:@"KeBiaoSecTableViewCell" bundle:nil] forCellReuseIdentifier:@"KeBiaoSecTableViewCell"];
        _listV.separatorStyle = 0;
    }
    return _listV;
}

-(KeBiaoTongJiV *)KebiaoV
{
    if (!_KebiaoV) {
        _KebiaoV = [[KeBiaoTongJiV alloc]initWithFrame:CGRectMake(0, 0, KscreenW, KscreenH-64)];
        _KebiaoV.alpha = 0;
    }
    return _KebiaoV;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationItem.title = @"我的课表";
}

-(UIButton *)custumBTN
{
    if (!_custumBTN)
    {
        _custumBTN = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _custumBTN.titleLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightThin];

        [_custumBTN setTitle:[NSString stringWithFormat:@"%@年%@月",year,month] forState:(UIControlStateNormal)];
        [_custumBTN setImage:[UIImage imageNamed:@"down_arrow"] forState:(UIControlStateNormal)];
        [_custumBTN setTitleEdgeInsets:UIEdgeInsetsMake(0, -50, 0, 0)];
        [_custumBTN setImageEdgeInsets:UIEdgeInsetsMake(0, 120, 0, 0)];

//        _custumBTN.titleLabel.font = [UIFont systemFontOfSize:20];
        [_custumBTN setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        _custumBTN.frame = CGRectMake(0, 0, 180, 60);
        [_custumBTN addTarget:self action:@selector(changDateAct) forControlEvents:(UIControlEventTouchUpInside)];

    }
    return _custumBTN;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHaveClick = NO;
    [self.view addSubview:self.listV];
    UIButton *statisticalbtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    statisticalbtn.frame = CGRectMake(0, 0, 40, 40);
    [statisticalbtn setTitle:@"统计" forState:(UIControlStateNormal)];
    [statisticalbtn addTarget:self action:@selector(TongjiAct) forControlEvents:(UIControlEventTouchUpInside)];
    statisticalbtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [statisticalbtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]initWithCustomView:statisticalbtn];
    self.navigationItem.rightBarButtonItem = rightBtn;
    [self.view addSubview:self.KebiaoV];
    page = 1;
    [self getDate];

    [self Request];
//    self.listV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        page++;
//        [self Request];
//    }];
//
//    self.listV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        page = 1;
//        [self Request];
//    }];
//    [self.listV.mj_header beginRefreshing];
}

-(void)TongjiAct
{
    if (self.isHaveClick== YES)
    {
          [self.KebiaoV apperyear:year month:month cid:self.cid];
    }else
    {
        [HUD showText:@"暂无课例" AfterTime:1];
    }
}

-(void)getDate
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    self.comp = [gregorian components: unitFlags
                             fromDate:dt];
    
    year = [NSString stringWithFormat:@"%02ld",self.comp.year];
    month = [NSString stringWithFormat:@"%02ld",self.comp.month];
    self.navigationItem.titleView = self.custumBTN;
}

-(void)Request
{
    [RequestManager RequstWithUrl:@"/index.php?g=App&m=TeacherIndex&a=courseTableall" parmDic:@{@"tid":[[NSUserDefaults standardUserDefaults]objectForKey:@"tid"],@"cid":self.cid,@"year":year,@"month":month,@"page":[NSString stringWithFormat:@"%ld",page]} requestType:RequestGET Success:^(id data)
    {
        NSArray *Arr = data;
        if (page == 1) {
            [self.ListArr removeAllObjects];
        }
        if (Arr.count==0) {
            page--;
        }
        [self.ListArr addObjectsFromArray:Arr];
        [self.listV reloadData];

        [self.listV.mj_header endRefreshing];
        [self.listV.mj_footer endRefreshing];

        if (Arr.count == 0||Arr.count<10)
        {
            self.listV.mj_footer.state = MJRefreshStateNoMoreData;
        }
        if (self.ListArr.count == 0)
        {
            self.isHaveClick = NO;
        }else
        {
            self.isHaveClick = YES;
        }
        
    } error:^(NSError *error)
    {

    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.ListArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *dataArr = self.ListArr[section][@"data_v"];
    
    return dataArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return FLT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return FLT_MIN;
}

//有没有上课

//是不是代课

// 

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 60;
    }else
    {
        return 60;
    }
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *sectionDic = self.ListArr[indexPath.section];
    NSArray *dataArr = sectionDic[@"data_v"];
    NSDictionary *rowDic = dataArr[indexPath.row];
    if (indexPath.row == 0)
    {
        KeBiaoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KeBiaoTableViewCell" forIndexPath:indexPath];
        cell.yearL.text = sectionDic[@"date_year"];
        cell.dateL.text = sectionDic[@"date_md"];
        cell.titleL.text = rowDic[@"detail"];
        cell.selectionStyle = 0;
        if (indexPath.section == 0)
        {
            [cell.topLine setHidden:YES];
        }else
        {
            [cell.topLine setHidden:NO];
        }
        if ([rowDic[@"status"]isEqualToString:@"1"])
        {
            cell.bgimage.image = [UIImage imageNamed:@"BlueTongji"];
            cell.titleL.textColor = [UIColor whiteColor];
        }else if([rowDic[@"status"] isEqualToString:@"4"])
        {
            cell.bgimage.image = [UIImage imageNamed:@"RedTongji"];
            cell.titleL.textColor = [UIColor whiteColor];
        }else if ([rowDic[@"status"] isEqualToString:@"3"])
        {
            cell.bgimage.image = [UIImage imageNamed:@"graytongji.png"];
            cell.titleL.textColor = UIColors(0x333333);
        }else if ([rowDic[@"status"] isEqualToString:@"2"])
        {
            cell.bgimage.image = [UIImage imageNamed:@"OrangeTongji"];
            cell.titleL.textColor = [UIColor whiteColor];
        }

        if (indexPath.section == 0) {
            [cell.topLine setHidden:YES];
        }else
        {
            [cell.topLine setHidden:NO];
        }

        if (indexPath.section == self.ListArr.count-1)
        {
            if (dataArr.count == 1)
            {
                [cell.bottomLine setHidden:YES];
            }else
            {
                [cell.bottomLine setHidden:NO];
            }
        }else
        {
            [cell.bottomLine setHidden:NO];
        }


        cell.selectionStyle = 0;
        return cell;
    }else
    {
        KeBiaoSecTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KeBiaoSecTableViewCell" forIndexPath:indexPath];
        if ([rowDic[@"status"]isEqualToString:@"1"])
        {
            cell.bgImageV.image = [UIImage imageNamed:@"BlueTongji"];
            cell.titleL.textColor = [UIColor whiteColor];
        }else if([rowDic[@"status"] isEqualToString:@"4"])
        {
            cell.bgImageV.image = [UIImage imageNamed:@"RedTongji"];
            cell.titleL.textColor = [UIColor whiteColor];
        }else if ([rowDic[@"status"] isEqualToString:@"3"])
        {
            cell.bgImageV.image = [UIImage imageNamed:@"graytongji.png"];
            cell.titleL.textColor = UIColors(0x333333);
        }else if ([rowDic[@"status"] isEqualToString:@"2"])
        {
            cell.bgImageV.image = [UIImage imageNamed:@"OrangeTongji"];
            cell.titleL.textColor = [UIColor whiteColor];
        }
        cell.titleL.text = rowDic[@"detail"];

        if (indexPath.section == self.ListArr.count-1)
        {
            [cell.LineV setHidden:YES];
        }else
        {
            [cell.LineV setHidden:NO];
        }
        cell.selectionStyle = 0;
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *sectionDic = self.ListArr[indexPath.section];
    NSArray *dataArr = sectionDic[@"data_v"];
    NSDictionary *rowDic = dataArr[indexPath.row];

    if ([rowDic[@"status"]isEqualToString:@"4"])
    {
        [HUD showText:@"该时段已请过假" AfterTime:1];
    }else if ([rowDic[@"status"]isEqualToString:@"1"])
    {
        [HUD showText:@"已经上过课的课程不能请假" AfterTime:1];
    }else if ([rowDic[@"status"]isEqualToString:@"2"])
    {
         [HUD showText:@"已经上过课的课程不能请假" AfterTime:1];
    }
    else
    {
        PopWindowView *poppicker = [[PopWindowView alloc]initWithCompleteBlock:^(NSString *conText)
                                    {
                                        [self Qingjia:conText aid:rowDic[@"aid"]indexpath:indexPath];
                                    }];
        poppicker.themeColor = [UIColor blueColor];
        poppicker.title = @"请假";
        poppicker.placehoder = @"请输入请假理由";
        poppicker.themeColor  =  UIColors(MainColor);
        [poppicker show];
    }
}

-(void)Qingjia:(NSString *)context aid:(NSString *)aid indexpath:(NSIndexPath *)indexpath
{
    [RequestManager HudRequestWithUrl:@"/index.php?g=App&m=TeacherIndex&a=askForleave" parmDic:@{@"aid":aid,@"remark":context} requestType:RequestPOST view:self.view Success:^(id data)
    {
        if (indexpath.row == 0)
        {
            KeBiaoTableViewCell *cell = (KeBiaoTableViewCell *)[self.listV cellForRowAtIndexPath:indexpath];
            cell.titleL.textColor = [UIColor whiteColor];
            cell.bgimage.image = [UIImage imageNamed:@"RedTongji"];
        }else
        {
            KeBiaoSecTableViewCell *cell = (KeBiaoSecTableViewCell *)[self.listV cellForRowAtIndexPath:indexpath];
            cell.titleL.textColor = [UIColor whiteColor];
            cell.bgImageV.image = [UIImage imageNamed:@"RedTongji"];
        }
         [self Request];
    } error:^(NSError *error)
    {
        
    }];
}


/**
 改变顶部日期的方法
 */
-(void)changDateAct
{
    DatePickerView *datepicker = [[DatePickerView alloc]initWithCompleteBlock:^(NSDate *selectDate) {
        [self.custumBTN setTitle:[NSString stringWithFormat:@"%@年%@月",year,month] forState:(UIControlStateNormal)];

        year = [selectDate stringWithFormat:@"yyyy"];
        month = [selectDate stringWithFormat:@"MM"];
        [self.custumBTN setTitle:[NSString stringWithFormat:@"%@年%@月",year,month] forState:(UIControlStateNormal)];

        [self Request];

    }];
    datepicker.themeColor = [UIColor blueColor];
    datepicker.datePickerStyle = DateStyleShowYearMonth;
    datepicker.dateType     = DateTypeStartDate;
    datepicker.title        = @"选择年月";
    datepicker.themeColor   = UIColors(MainColor);
    datepicker.minLimitDate = [NSDate date:@"2017-01-01" WithFormat:@"yyyy-MM-dd"];
    datepicker.maxLimitDate = [NSDate date:@"2025-01-01" WithFormat:@"yyyy-MM-dd"];
    [datepicker show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
